/*
 * Copyright (C) 2010 Mamadou Diop.
 *
 * Contact: Mamadou Diop <diopmamadou(at)doubango.org>
 *	
 * This file is part of imsdroid Project (http://code.google.com/p/imsdroid)
 *
 * imsdroid is free software: you can redistribute it and/or modify it under the terms of 
 * the GNU General Public License as published by the Free Software Foundation, either version 3 
 * of the License, or (at your option) any later version.
 *	
 * imsdroid is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
 * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  
 * See the GNU General Public License for more details.
 *	
 * You should have received a copy of the GNU General Public License along 
 * with this program; if not, write to the Free Software Foundation, Inc., 
 * 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 *
 */

package org.doubango.FrCall.Screens;

import java.io.File;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;

import org.doubango.FrCall.AppConfig;
import org.doubango.FrCall.Engine;
import org.doubango.FrCall.FrCall;
import org.doubango.FrCall.Main;
import org.doubango.FrCall.OpenfireNetService;
import org.doubango.FrCall.OpenfireRosterService;
import org.doubango.FrCall.R;
import org.doubango.FrCall.Screens.chat.ScreenChat;
import org.doubango.FrCall.Services.IScreenService;
import org.doubango.FrCall.Utils.DialogUtil;
import org.doubango.FrCall.Utils.LogDebugger;
import org.doubango.FrCall.model.User;
import org.doubango.ngn.media.NgnMediaType;
import org.doubango.ngn.model.NgnHistoryEvent.StatusType;
import org.doubango.ngn.model.NgnHistorySMSEvent;
import org.jivesoftware.smack.Chat;
import org.jivesoftware.smack.ChatManagerListener;
import org.jivesoftware.smack.MessageListener;
import org.jivesoftware.smack.Roster;
import org.jivesoftware.smack.RosterEntry;
import org.jivesoftware.smack.RosterGroup;
import org.jivesoftware.smack.XMPPConnection;
import org.jivesoftware.smack.XMPPException;
import org.jivesoftware.smack.packet.Message;
import org.jivesoftware.smack.packet.Presence;
import org.jivesoftware.smack.packet.Presence.Type;
import org.jivesoftware.smackx.Form;
import org.jivesoftware.smackx.ReportedData;
import org.jivesoftware.smackx.ReportedData.Row;
import org.jivesoftware.smackx.ServiceDiscoveryManager;
import org.jivesoftware.smackx.filetransfer.FileTransfer;
import org.jivesoftware.smackx.filetransfer.FileTransferListener;
import org.jivesoftware.smackx.filetransfer.FileTransferManager;
import org.jivesoftware.smackx.filetransfer.FileTransferNegotiator;
import org.jivesoftware.smackx.filetransfer.FileTransferRequest;
import org.jivesoftware.smackx.filetransfer.IncomingFileTransfer;
import org.jivesoftware.smackx.packet.VCard;
import org.jivesoftware.smackx.search.UserSearchManager;
import org.jivesoftware.smackx.workgroup.packet.UserID;

import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Color;
import android.graphics.ColorMatrix;
import android.graphics.ColorMatrixColorFilter;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.style.ForegroundColorSpan;
import android.text.style.TextAppearanceSpan;
import android.util.Log;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.BaseExpandableListAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ExpandableListView;
import android.widget.ExpandableListView.ExpandableListContextMenuInfo;
import android.widget.ExpandableListView.OnChildClickListener;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ImageView.ScaleType;
import android.widget.TextView;
import android.widget.Toast;
/**
 * 好友界面
 *
 */
public class ScreenFriendList extends BaseScreen {

	private static String TAG = ScreenFriendList.class.getCanonicalName();
	public static String[] GROUPS = {"陌生人","买卖","好友","亲人","同事","同学"};
	private ExpandableListView listView;
	private ScreenFriendAdapter adapter;	
	
	private List<String> group;
	private List<List<User>> child;
	public static List<User> recent_friends;
	private final static int MENU_LBS = 3;
	private Button btPhone,btManage,btAdd;
//	TextView nickname_txt,usersign_txt;
	EditText searchString;
	ImageView usericon_img;
	ImageButton turn2myInfo_Btn,search_button;
	public static VCard mCard;
	public static boolean needRefreshList = false;

	public ScreenFriendList() {
		super(SCREEN_TYPE.FRIEND_LIST_T, TAG);
	}
	BroadcastReceiver br = new BroadcastReceiver() {
		
		@Override
		public void onReceive(Context context, Intent intent) {
			if(intent.getAction().equals(getResources().getString(R.string.OPENFIRE_ACTION_NOTIFY_REFRESH_ROSTER)))
			{
				if(roster == null)
					roster = OpenfireRosterService.roster;
				needRefreshList = intent.getBooleanExtra(getResources().getString(R.string.REFRESH_ROSTER_LIST),false);
				if(needRefreshList)
				{
					getFriends();
//					ListHander.sendEmptyMessage(SCREEN_HOME_HANDLE_REFRESH_LIST_VIEW);
					needRefreshList = false;
				}
			}
		}
	};
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.screen_friend_list);
		startService(new Intent(getBaseContext(), OpenfireRosterService.class));
		final IntentFilter intentFilter = new IntentFilter();
		intentFilter.addAction(getResources().getString(R.string.OPENFIRE_ACTION_NOTIFY_REFRESH_ROSTER));
		//为广播接收器添加IntentFilter
	    registerReceiver(br, intentFilter);
	    btPhone=(Button) findViewById(R.id.to_contacts_btn_on_friend_page);
	    btPhone.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Autogenerated method stub
				Intent i=new Intent(getApplicationContext(), ScreenHistoryCall.class);
				startActivity(i);
			}
		});
	    btManage=(Button) findViewById(R.id.nav_friend_manage);
	    btManage.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				Intent i=new Intent(getApplicationContext(),ManageFriendSelectPage.class);
				startActivity(i);
			}
		});
	    btAdd=(Button) findViewById(R.id.nav_search_friend);
	    btAdd.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				Intent i=new Intent(getApplicationContext(),SearchFriendPage.class);
				startActivity(i);
			}
		});
//		BaiduMapService.init(this);
//		BaiduMapService.start();

		// 文件接收监听器（Openfire：服务器，Net:网络,Connection:连接）
		setFileListener(OpenfireNetService.getXMPPConnection());		
		// 聊天接收监听（chat：闲谈，与…搭讪）
		OpenfireNetService.getXMPPConnection().getChatManager().addChatListener(new ChatManagerListener() {			
			@Override//Created：创造的；引起的
			public void chatCreated(Chat chat, boolean createdLocally) {
				if(!createdLocally) {
						//添加消息监听器
					chat.addMessageListener(new MessageListener() {
						//process:过程,进行,方法
						@Override
						public void processMessage(Chat chat, Message msg) {
							
							final IScreenService screenService = ((Engine)Engine.getInstance()).getScreenService();
							final IBaseScreen currentScreen = screenService.getCurrentScreen();
							
							if (currentScreen.getType() != SCREEN_TYPE.NEW_MSG_T) {
								Main.sMsgCount++;
								ListHander.sendEmptyMessage(SCREEN_HOME_HANDLE_REFRESH_NEW_MSG);
							}
							
							// 收消息
							String JID = msg.getFrom();
							/*
							 * indexOf(int ch)  返回指定字符在此字符串中第一次出现处的索引
							 * 
							 * substring(int beginIndex,int endIndex)返回一个新字符串，它是此字符串
							 * 的一个子字符串。该子字符串从指定的 beginIndex 处开始，直到索
							 * 引 endIndex - 1 处的字符。因此，该子字符串的长度为 endIndex-beginIndex。
                             *beginIndex - 起始索引（包括）endIndex - 结束索引（不包括）。 
							 */
							String from = JID.substring(0, JID.indexOf("/"));
							NgnHistorySMSEvent event = new NgnHistorySMSEvent(from, StatusType.Incoming);
							event.setContent(msg.getBody());
							/*
							 * body: 身体；主体；大量；团体
							 * engine:引擎，发动机,history:史籍,往事,史册 
							 */
							getEngine().getHistoryService().addEvent(event);
							ScreenChat.currentChatList.add(event);
							if(ScreenChat.instance!=null)
								ScreenChat.instance.refreshFromServer();
							User user = getUserByName(from);
							if (user == null) {								
								VCard mCard = new VCard();
								mCard = OpenfireNetService.getVcard(from);
								if(mCard !=null)
								{
									user = new User(from, mCard);
									user.setJID(JID);
								}								
							}	
							ScreenNewMessage.addMessage(event, user);
							LogDebugger.debug(TAG, "" + msg.getFrom() + ":" + msg.getBody());							
						}
					});
				}
			}
		});
		
//		refreshlist();
		adapter = new ScreenFriendAdapter(this);
		if(group ==null)
		{
			group = new ArrayList<String>();   
	//        child = new ArrayList<List<User>>(); 
	//		getFriends();
			for(int i = 0;i<GROUPS.length;i++)
			{
				group.add(GROUPS[i]+"[0/0]");
			}
			//getFriends();
		}
		listView = (ExpandableListView) findViewById(R.id.screen_friend_list_content);
		listView.setAdapter(adapter);
		listView.setOnItemSelectedListener(new ExpandableListView.OnItemSelectedListener(){

			@Override
			public void onItemSelected(AdapterView<?> adv, View v,
					int pos, long id) {
				System.out.println("itemselect v = "+v.getId());
			}

			@Override
			public void onNothingSelected(AdapterView<?> adv) {
				// TODO Auto-generated method stub
				System.out.println("Nothing");
			}
			
		});
		listView.setOnChildClickListener(new OnChildClickListener() {
			
			@Override
			public boolean onChildClick(ExpandableListView parent, View v,
					int groupPosition, int childPosition, long id) {
				
				{
					User user = (User) listView.getExpandableListAdapter().getChild(groupPosition, childPosition);
//					VCard vCard = new VCard();
//					try {
//						vCard.load(mOpenfireService.getXMPPConnection(), user.getUserId());
//					} catch (XMPPException e) {
//						// TODO Auto-generated catch block
//						e.printStackTrace();
//					}
//					selFriend = null;
					selFriend = user;
					listView.showContextMenu();
//					mScreenService.show(ScreenChat.class,null,true);
//					startActivity(new Intent(ScreenHome.this,ScreenChat.class));
					return true;
				}
			}
		});
		refresh();
//		searchString = (EditText) findViewById(R.id.screen_friend_list_search_string);
//		search_button = (ImageButton) findViewById(R.id.screen_friend_list_search_button);
//		search_button.setOnClickListener(new OnClickListener() {
//			
//			@Override
//			public void onClick(View v) {
//				ScreenFriendSearchLocal.searchStr = searchString.getText().toString();
//				if(ScreenFriendSearchLocal.searchStr.trim().equals(""))
//					return;
//				else
//				{
//					if(mInputMethodManager!=null && mInputMethodManager.isActive() && ScreenHome.this.getCurrentFocus()!=null){
////						BaseScreen.mInputMethodManager.toggleSoftInput(0, InputMethodManager.HIDE_IMPLICIT_ONLY);
//						mInputMethodManager.hideSoftInputFromWindow(ScreenHome.this.getCurrentFocus().getWindowToken(),
//								InputMethodManager.HIDE_NOT_ALWAYS);
//					}
//					mScreenService.show(ScreenFriendSearchLocal.class, null, "查询结果");
//				}
//			}
//		});
//		listView.setOnGroupClickListener(new OnGroupClickListener() {
//			
//			@Override
//			public boolean onGroupClick(ExpandableListView exV, View v, int pos,
//					long id) {
//				Drawable groupIndicator = ScreenFriendList.this.getResources().getDrawable(R.drawable.list_open);
//				exV.setGroupIndicator(groupIndicator );
//				return true;
//			}
//		});
//		listView.setOnChildClickListener(new OnChildClickListener() {
//			
//			@Override
//			public boolean onChildClick(ExpandableListView exV, View v, int arg2,
//					int arg3, long arg4) {
//				return false;
//			}
//		});
//		listView.setOnGroupExpandListener(new OnGroupExpandListener() {
//			
//			@Override
//			public void onGroupExpand(int pos) {
//				System.out.println("pos = "+pos);
//			}
//		});
//		turn2myInfo_Btn = (ImageButton) findViewById(R.id.screen_friend_list_check_myInfo_IMB);
//		turn2myInfo_Btn.setOnClickListener(new View.OnClickListener() {
//			
//			@Override
//			public void onClick(View v) {
//				selFriend = new User((mOpenfireService.getXMPPConnection().getUser()),mCard);
//				mScreenService.show(ScreenUserSettings.class, null, "个人设置");
//			}
//		});
		registerForContextMenu(listView);
	}

	/**
	 * 根据名字获取user实例
	 */
	private User getUserByName(String from) {
		for (List<User> item : child) {
			for (User user : item) {
				if (from.equals(user.getUserId())) {
					return user;
				}
			}
		}
		return null;
	}
//	public void handleItemSelect(int item){
//
//		switch(item){
//			case BaseScreen.MENU_ADD_FRIEND:
//////				if(menuDialog==null)
////					menuDialog = new AlertDialog.Builder(this).create();
////				if(dialogEditText == null)
////					dialogEditText = new EditText(this);
////				dialogEditText.setHint("请输入好友名称");
////				menuDialog.setTitle("添加好友");
////				menuDialog.setView(dialogEditText);
////				menuDialog.setButton("确定", new DialogInterface.OnClickListener() {
////	
////					@Override
////					public void onClick(DialogInterface dialog, int which) {
////						// TODO Auto-generated method stub
////						addFriendId = dialogEditText.getText().toString();
////						addfriend();
////					}
////				});
////				menuDialog.setButton2("取消", new DialogInterface.OnClickListener() {
////					
////					@Override
////					public void onClick(DialogInterface dialog, int which) {
////						menuDialog.dismiss();
////					}
////				});
////				menuDialog.show();
//				mScreenService.show(ScreenFriendSearch.class, null, "查询好友");
//				break;
//			case BaseScreen.MENU_REFRESH_LIST:
//				roster.reload();
//				break;
//			case BaseScreen.MENU_SIGN:
//				menuDialog = new AlertDialog.Builder(this).create();
//				dialogEditText = new EditText(this);
//				dialogEditText.setHint("请输入个人签名");
//				dialogEditText.setText(FrCall.user.getIdiograph());
//				menuDialog.setTitle("修改签名");
//				menuDialog.setView(dialogEditText);
//				menuDialog.setButton("确定", new DialogInterface.OnClickListener() {
//	
//					@Override
//					public void onClick(DialogInterface dialog, int which) {
//						FrCall.user.setIdiograph(dialogEditText
//								.getText().toString());
//						FrCall.user.save();
//						usersign_txt.setText(FrCall.user.getIdiograph());
//						BaseScreen.mInputMethodManager.hideSoftInputFromWindow(dialogEditText.getWindowToken(), 0);
//					}
//				});
//				menuDialog.setButton2("取消", new DialogInterface.OnClickListener() {
//					
//					@Override
//					public void onClick(DialogInterface dialog, int which) {
//						menuDialog.dismiss();
//						BaseScreen.mInputMethodManager.hideSoftInputFromWindow(dialogEditText.getWindowToken(), 0);
//					}
//				});
//				menuDialog.show();
//				break;
//			case BaseScreen.MENU_ABOUT:
////				menuView = View.inflate(this, R.layout.screen_about, null);
////				TextView aboutText = (TextView) menuView.findViewById(R.id.screen_about_textView_copyright);
////				// 创建AlertDialog
////				if(menuDialog==null)
////					menuDialog = new AlertDialog.Builder(this).create();
////				menuDialog.setView(menuView);
////				menuDialog.show();
//				mScreenService.show(ScreenAbout.class,null,"关于");
//			break;
//			case BaseScreen.MENU_EXIT:
//				CustomDialog.show(this, R.drawable.exit_48, "是否退出", "是否退出", "确定", new OnClickListener() {
//					@Override
//					public void onClick(View v) {
//						CustomDialog.dialog.dismiss();
//						((Main)(getEngine().getMainActivity())).exit();
//						getEngine().stop();
//						stopService(((Main)(getEngine().getMainActivity())).getIntent());
//						finish();
//					}
//				}, "取消", new OnClickListener() {
//					
//					@Override
//					public void onClick(View v) {
//						CustomDialog.dialog.dismiss();
//					}
//				});
//				break;
//			case BaseScreen.MENU_SETTINGS:
//				mScreenService.show(ScreenSystemSettings.class,null,"系统设置");
//				//mScreenService.show(ScreenSimpleSetting.class,null,"网络设置");
//				break;
//		}
//		Main.softMenu_pad.animateClose();
//	}
	private void refresh() {
		String userID = mOpenfireService.getLoginUser();
		if(mCard==null)
		{
			mCard = FrCall.user.getvCard();
//		try {
//			mCard.load(mOpenfireService.getXMPPConnection());
//			Collection<String> myInfos = mOpenfireService.getXMPPConnection().getAccountManager().getAccountAttributes();
//			for(String myInfo: myInfos)
//			{
//				System.out.println("myInfo:"+myInfo);
//			}
////			if(mCard.getEmailHome()=="")
////			{
////				
////				mCard.setEmailHome("holybomb@163.com");
////			}
//		} catch (XMPPException e) {
//			e.printStackTrace();
//		}
		}
		User myself = FrCall.user;
//		nickname_txt = (TextView) findViewById(R.id.screen_friend_list_neckname_text);
//		usersign_txt = (TextView) findViewById(R.id.screen_friend_list_usersign_text);
//		usersign_txt.setText(myself.getIdiograph());
		
		
//		edit by xiaozhang
//		myself.setNickName(mCard.getNickName());
		myself.setNickName("888888");
//		nickname_txt.setText(myself.getDisplayName());
//		byte[] usericon_data = mCard.getAvatar();
//		if(usericon_data!=null)
//		{
//			Bitmap usericon = BitmapFactory.decodeByteArray(usericon_data, 0, usericon_data.length);
//			usericon_img = (ImageView) findViewById(R.id.screen_friend_list_usericon_img);
//			usericon_img.setImageBitmap(usericon);
//		}
		FrCall.user = myself;
		// get friends from service

		// TEST
//		if(group ==null)
//		{
//			group = new ArrayList<String>();   
//	//        child = new ArrayList<List<User>>(); 
//	//		getFriends();
//			for(int i = 0;i<GROUPS.length-1;i++)
//			{
//				group.add(GROUPS[i]+"[0/0]");
//			}
//			getFriends();
//		}
//		else
//		{
//			getFriends();
//		}
	}
	@Override
	public boolean onMenuOpened(int featureId, Menu menu) {
		
		return false;
	}
	@Override
	public void onCreateContextMenu(ContextMenu menu, View v,
			ContextMenuInfo menuInfo) {
		ExpandableListContextMenuInfo mi = (ExpandableListContextMenuInfo)menuInfo;
//		int type = ExpandableListView.getPackedPositionType(mi.packedPosition);
//		if (type == ExpandableListView.PACKED_POSITION_TYPE_CHILD) {
//			menu.add(0, MENU_VOICE, Menu.NONE, "语音对话");
//			menu.add(0, MENU_VIDEO, Menu.NONE, "视频聊天");
//			menu.add(0, MENU_MSG, Menu.NONE, "文本聊天");
			menu.add(0, MENU_LBS, Menu.NONE, "好友位置");
			
			int groupPos = ExpandableListView.getPackedPositionGroup(mi.packedPosition);
			int childPos = ExpandableListView.getPackedPositionChild(mi.packedPosition);
		selFriend = child.get(groupPos).get(childPos);
//			
//			String str = "您选中了第 " + groupPos + " 组的第 " + childPos +" 个好友";
//			LogDebugger.debug(TAG, str);
//		}
	}
	
    @Override
	public boolean onContextItemSelected(MenuItem item) {
		switch (item.getItemId()) {
//		case MENU_VOICE:
//			ScreenAV.makeCall(selFriend.getUserName()+"", NgnMediaType.Audio);
//			break;
//		case MENU_VIDEO:
//			ScreenAV.makeCall(selFriend.getUserName()+"", NgnMediaType.AudioVideo);
//			break;
//		case MENU_MSG:
////			ScreenChat.startChat(selFriend.getUserId()+"", !false);
//			mScreenService.show(ScreenChat.class,null,true);
//			FrCall.s_OppID = selFriend.getUserId()+"";
//			break;
		case MENU_LBS:
			break;
		}
		String str = "您单击了" + item.getItemId();
		LogDebugger.debug(TAG, str);
		return true;
	}
    @Override
    public boolean hasMenu() {
    	// TODO Auto-generated method stub
    	return true;
    }
    
    @Override
    public boolean hasBack() {
    	return true;
    }
    @Override
    public boolean back() {
//    	if(Main.softMenu_pad.isOpened())
//    	{
//    		Main.softMenu_pad.animateClose();
//    		return true;
//    	}
//    	else
    	{
    		return super.back();
    	}
    }
    @Override
    public void onBackPressed() {
//    	if(Main.softMenu_pad.isOpened())
//    	{
//    		Main.softMenu_pad.animateClose();
//    	}
//    	else
    	{
    		super.onBackPressed();
    	}
    }
//    @Override
//	public boolean createOptionsMenu(Menu menu) {
//    	Main.softMenu_pad.setVisibility(View.VISIBLE);
//		Main.softMenu_pad.animateToggle();
//		Main.softMenu_pad_info.setOnItemClickListener(new OnItemClickListener() {
//
//			@Override
//			public void onItemClick(AdapterView<?> adv, View v, int pos,
//					long id) {
//				handleItemSelect(pos);
//			}
//		});
////		for (int i = 0; i < menu_name_array.length; i++) {
////			menu.add(0, i, 0, menu_name_array[i]).setIcon(menu_image_array[i]);
////		}
//		return !true;
//	}
    public void refreshlist(){
//		pDialog.setTitle("请稍后");
//		pDialog.setMessage("正在刷新好友...");
//		pDialog.setCancelable(true);
//		pDialog.show();
//    	this.showInProgress("正在刷新好友...", true, true);
    	Thread refreshing = new Thread(new Runnable() {
 			
 			@Override
 			public void run() {
 				roster.reload();
 				//getFriends();
 				needRefreshList = false;
 				ListHander.sendEmptyMessage(SCREEN_HOME_HANDLE_REFRESH_LIST_VIEW);
 			}
 		});
    	synchronized (refreshing) {
    		refreshing.start();
		}
    	 
    }
	public void addfriend() {
		// pDialog.setTitle("请稍后");
		// pDialog.setMessage("正在刷新好友...");
		// pDialog.setCancelable(true);
		// pDialog.show();
		this.showInProgress("正在添加好友...", true, true);
		new Thread(new Runnable() {

			@Override
			public void run() {
				try {
					UserSearchManager search = mOpenfireService.getUserSearchManager();
					String searchService = mOpenfireService.getUserSearchService();
					Form searchForm = search
							.getSearchForm(searchService);
					Form answerForm = searchForm.createAnswerForm();
					answerForm.setAnswer("Username", true);
					answerForm.setAnswer("search", addFriendId);
					ReportedData data = search.getSearchResults(answerForm,
							searchService);
					Iterator<Row> it = data.getRows();
					Row row = null;
					toastText="";
					while (it.hasNext()) {
						row = (Row) it.next();
						toastText += row.getValues("Username").next().toString()
								+ " ";
						Log.i("Username",row.getValues("Username").next().toString());
					}
					if(toastText.length()>0)
					{
						needRefreshList = true;
						roster.createEntry(addFriendId+"@"+mOpenfireService.getXMPPConnection().getServiceName(), addFriendId, new String[] { "陌生人" });
						Presence pre = new Presence(Presence.Type.subscribe);
						pre.setFrom(mOpenfireService.getXMPPConnection().getUser());
						pre.setTo(new UserID(addFriendId).toString());
						mOpenfireService.getXMPPConnection().sendPacket(pre);
						toastText = "添加成功";
						ListHander.sendEmptyMessage(SCREEN_HOME_HANDLE_TOAST_SHOW_LIST);
					}
					else
					{
						toastText = "无此好友";
						ListHander.sendEmptyMessage(SCREEN_HOME_HANDLE_TOAST_SHOW_LIST);
					}
					cancelInProgress();
				} catch (Exception e) {
					toastText = e.getMessage() + " " + e.getClass().toString();
					ListHander
					.sendEmptyMessage(SCREEN_HOME_HANDLE_TOAST_SHOW_LIST);
				}

				
			}
		}).start();
	}
	public static String toastText = "";
	public static int toastTime = Toast.LENGTH_SHORT;
	
	final public static int SCREEN_HOME_HANDLE_REFRESH_LIST_VIEW = 0;
	final public static int SCREEN_HOME_HANDLE_TOAST_SHOW_LIST = 2;
	final public static int SCREEN_HOME_HANDLE_REFRESH_NEW_MSG = 3;
	final public static int SCREEN_HOME_HANDLE_FILE_TRANSFER = 4;
	final public static int SCREEN_HOME_HANDLE_FILE_RECEIVE = 5;
	
	private static String sTip = "";
	private static FileTransferRequest sRequest;
	
    private static final int MAX_PROGRESS = 100;
    
    private static ProgressDialog mProgressDialog;
    private int mProgress;
	private boolean mHasClick;
	
	private Handler ListHander = new Handler() {

		public void handleMessage(android.os.Message msg) {
			switch (msg.what) {
			case SCREEN_HOME_HANDLE_REFRESH_LIST_VIEW:
				adapter.notifyDataSetChanged();
				break;

			case SCREEN_HOME_HANDLE_TOAST_SHOW_LIST:
				Toast.makeText(getApplicationContext(), toastText, toastTime).show();
				break;

			case SCREEN_HOME_HANDLE_REFRESH_NEW_MSG:
				Main.mTVMsgCount.setText(Main.sMsgCount + "");
				Main.mTVMsgCount.setVisibility(View.VISIBLE);
				Main.mTVMsgCount.invalidate();
				break;
				
			case SCREEN_HOME_HANDLE_FILE_RECEIVE:
				if (mProgressDialog == null) {
					mProgressDialog = new ProgressDialog(ScreenFriendList.this);
					mProgressDialog.setIcon(R.drawable.jia);
					mProgressDialog.setTitle("接收文件中...");
					mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
					mProgressDialog.setMax(MAX_PROGRESS);
					mProgressDialog.setCancelable(false);									
				}
				mProgressDialog.show();
				mProgressDialog.setProgress(0);
				break;
				
			case SCREEN_HOME_HANDLE_FILE_TRANSFER:
				mHasClick = false;
				final Dialog dialog = DialogUtil.openMsgDialog(
						ScreenFriendList.this,
						R.drawable.jia,
						sTip,
						"确定",
						"取消",
						new DialogInterface.OnClickListener() {

							@Override
							public void onClick(
									DialogInterface dialog,
									int which) {
								mHasClick = true;
								// 接受
								final IncomingFileTransfer transfer = sRequest.accept();
								File filePath;
								
								// 有SD卡
								if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
									filePath = new File(AppConfig.SD_FOLDER);
								} else {
									filePath = ScreenFriendList.this.getFilesDir();
								}
								if(!filePath.exists())
								{
									filePath.mkdir();
								}
								File file = new File(filePath, sRequest.getFileName());
								if (!file.exists()) {
									try {
										file.createNewFile();
									} catch (Exception e) {
										e.printStackTrace();
									}
								}
								
								try {
									transfer.recieveFile(file);
								} catch (XMPPException e) {
									e.printStackTrace();
								}
								if (mProgressDialog == null) {
									mProgressDialog = new ProgressDialog(ScreenFriendList.this);
									mProgressDialog.setIcon(R.drawable.jia);
									mProgressDialog.setTitle("接收文件中...");
									mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
									mProgressDialog.setMax(MAX_PROGRESS);
									mProgressDialog.setCancelable(false);									
								}
								// 接收进度
								new Thread () {
									public void run() {
										
										FileTransfer.Status temp = null;
										
										while(true) {
											
											if (temp != transfer.getStatus()) {
												temp = transfer.getStatus();
												LogDebugger.debug(TAG, "传送文件当前状态：" + temp);
											}					
											
											if (transfer.getStatus() == FileTransfer.Status.cancelled) {
												toastText = "对方取消了";
												ListHander.sendEmptyMessage(SCREEN_HOME_HANDLE_TOAST_SHOW_LIST);
												mProgressDialog.cancel();
												String history = toastText +"\"" + sRequest.getFileName() + "\"(" + sRequest.getFileSize() + "byte)的传送，文件接收失败。 ";
												receiveFileHistory(history);
												break;
												
											} else if (transfer.getStatus() == FileTransfer.Status.error) {
												toastText = "接收文件出现异常";
												ListHander.sendEmptyMessage(SCREEN_HOME_HANDLE_TOAST_SHOW_LIST);
												mProgressDialog.cancel();
												String history = "接收" +"\"" + sRequest.getFileName() + "\"(" + sRequest.getFileSize() + "byte)出现异常，文件接收失败。 ";
												receiveFileHistory(history);
												break;
												
											} else if (transfer.getStatus() == FileTransfer.Status.negotiated) {
												ListHander.sendEmptyMessage(SCREEN_HOME_HANDLE_FILE_RECEIVE);							
												
											} else if (transfer.getStatus() == FileTransfer.Status.in_progress) {
												LogDebugger.debug(TAG, "传送文件当前状态：" + transfer.getProgress());
												// 接受文件中...
												mProgress = (int)(transfer.getProgress() * 100);
												if(mProgressDialog!=null)
													mProgressDialog.setProgress(mProgress);	
												
											} else if (transfer.getStatus() == FileTransfer.Status.complete) {
												toastText = "接收文件完成";
												ListHander.sendEmptyMessage(SCREEN_HOME_HANDLE_TOAST_SHOW_LIST);
												mProgressDialog.dismiss();
												String history = "成功接收" +"\"" + sRequest.getFileName() + "\"(" + sRequest.getFileSize() + "byte) ";
												receiveFileHistory(history);
												break;
											}
										}
									}
								}.start();
							}
						},
						new DialogInterface.OnClickListener() {

							@Override
							public void onClick(
									DialogInterface dialog,
									int which) {
								mHasClick = true;
								// 拒绝
								sRequest.reject();
								String history = "您拒绝了" +"\"" + sRequest.getFileName() + "\"(" + sRequest.getFileSize() + "byte)的接收，文件接收失败。 ";
								receiveFileHistory(history);
							}
						});
				
				dialog.show();
				
				// 检测对方取消
				new Thread() {
					public void run() {
						
						FileTransfer.Status temp = null;
						final IncomingFileTransfer transfer = sRequest.accept();
						
						while (true) {

							if (temp != transfer.getStatus()) {
								temp = transfer.getStatus();
								LogDebugger.debug(TAG, "传送文件当前状态：" + temp);
							}

							if (transfer.getStatus() == FileTransfer.Status.cancelled) {
								toastText = "对方取消了";
								ListHander
										.sendEmptyMessage(SCREEN_HOME_HANDLE_TOAST_SHOW_LIST);
								mProgressDialog.cancel();
								String history = toastText + "\""
										+ sRequest.getFileName() + "\"("
										+ sRequest.getFileSize()
										+ "byte)的传送，文件接收失败。 ";
								receiveFileHistory(history);
								dialog.dismiss();
								break;
							} else if (mHasClick) {
								break;
							}
						}
					}
				}.start();
				break;				
			default:
				// do something11.
				break;
			}
		}
	};
	
	
	public static String addFriendId = "";
	public static EditText dialogEditText;
//	@Override
//	public boolean onOptionsItemSelected(MenuItem item) {
//		handleItemSelect(item.getItemId());
//		return !true;
//	}
    
	protected void onResume() {
		super.onResume();
//		roster.reload();
		refresh();
		if(roster!=null)
			getFriends();
		needRefreshList=true;
	}

	protected void onDestroy() {
		unregisterReceiver(br);
		super.onDestroy();
	}

	private void getFriends() {

//		if (group == null) {
//			String requestUri = RequestConstant.getFriendsGroup();
//
//			RequestExecutor.doAsync(new Request(requestUri) {
//				@Override
//				protected void onSuccess(Map<?, ?> map) {
//					group = (ArrayList<String>) map.get("data");
//				}
//			});
//		}
//
//		if (child == null) {
//			String requestUri = RequestConstant.getMyFriends();
//
//			RequestExecutor.doAsync(new Request(requestUri) {
//				@Override
//				protected void onSuccess(Map<?, ?> map) {
//					child = (List<List<User>>) JsonUtils.bindDataListList(
//							map.get("data"), User.class);
//				}
//			});		
//		}
		// TEST
		group = new ArrayList<String>();   
        child = new ArrayList<List<User>>();   
        for(int i =0;i<GROUPS.length;i++)
        {
        	addInfo(GROUPS[i], roster);
        }
        //empty:空的
        ListHander.sendEmptyMessage(SCREEN_HOME_HANDLE_REFRESH_LIST_VIEW);
//        addInfo("在线好友", new String[]{"一凡","吕岩","小泽xiaoze","泰坦","尼桑"});   
//        addInfo("我的好友", new String[]{"Amy小妹","泰国妹","Taiwan", "撒旦法", "发到"});   
	}
	
	public void addInfo(String p,Roster c){     
        int totalNum = 0;//total：总数
        int onlineNum = 0;//online：在线
        List<User> item = new ArrayList<User>(); 
        User obj = null;
        Collection<RosterEntry> entries = c.getEntries();
        //Collection:采集收藏品,entry:进入，Roster：名册
//        int count = c.getUnfiledEntryCount();
//        if(count > 0)
//        {
//        	Collection<RosterEntry> unFiledEntries = c.getUnfiledEntries();
//        	for (RosterEntry entry : unFiledEntries) {
//        		SystemMessage message;
//				{
//					Presence pre = c.getPresence(entry.getUser());
//					message = new SystemMessage(FrCall.user.getUserId(),pre.getFrom(),pre.getTo(),pre.getType().toString(),true);
//					BaseScreen.sysDB.insert(message);
//					Main.sMsgCount++;
//				}
//        	}
//			ListHander.sendEmptyMessage(SCREEN_HOME_HANDLE_REFRESH_NEW_MSG);
//        }
        for (RosterEntry entry : entries) {
//        	int id = 1000+i;
//        	String userID = id + "";     
        	Collection<RosterGroup> Groups = entry.getGroups();
        	for (RosterGroup group : Groups) {
	        	if((group.getName().equals(p)&& !p.equals("最近联系人") )|| (p.equals("陌生人") && !p.contains(group.getName())))
	        	{
	        		//Presence：存在，出席
	        		Presence pre = c.getPresence(entry.getUser());
//	        		VCard vCard = new VCard();
//	        		try {
//						vCard.load(mOpenfireService.getXMPPConnection(), entry.getUser());
//					} catch (XMPPException e) {
//						e.printStackTrace();
//					}
		        	obj = new User();
		        	Type typeName = pre.getType();
		        	// 完整的JID
		        	String JID = pre.getFrom();
		        	obj.setNickName(entry.getUser());
		        	obj.setNoteName(entry.getName());
		        	obj.setUserId(entry.getUser());
		        	obj.setJID(JID);
		        	obj.setOnlineStatus(typeName);
		//        	if(!FrCall.s_MyUserID.equals(""+userID))
		        	item.add(obj);
		        	totalNum++;
		        	if(typeName == Type.available)
		        	{
		        		onlineNum++;
		        	}
	        	}
        	}
        }
        if(recent_friends==null)
        	recent_friends = new ArrayList<User>();
        if(p.equals("最近联系人") && obj!=null)
        {
        	recent_friends.add(obj);
        }
        else
        {
	        group.add(p+"  ["+onlineNum+"/"+totalNum+"]"); 
	        child.add(item);
        }
    } 

	
	private class ViewHolder {
		ImageView icon;
		TextView name;
		TextView id;
		ImageButton ivLook,ivSay,ivMsg;
	}
	private class GroupViewHolder {
		ImageView icon;
		TextView name;
	}
	/*
	 * BaseExpandableListAdapter:基类为ExpandableListAdapter用于提供数据和
	 * 一些数据到一个可扩展的列表视图的意见。
	 * expandable:可张开的，base：以…作基础
	 */
	private class ScreenFriendAdapter extends BaseExpandableListAdapter {
		
		private final Activity activity;
		protected LayoutInflater mLayoutInflater;
		private ViewHolder holder;
		private GroupViewHolder groupHolder;
		public ScreenFriendAdapter(Activity a) {
			activity = a;
			mLayoutInflater = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		}
		//获取的组数
		@Override
		public int getGroupCount() {
			if(group == null)
				return 0;
			else
				return group.size();
		}
		//取得规定组中元素的数量。
		@Override
		public int getChildrenCount(int groupPosition) {
			if(child==null)
				return 0;
			else
				return child.get(groupPosition).size();
		}
		//获取与特定组相关的数据
		@Override
		public String getGroup(int groupPosition) {
			if(group == null)
				return null;
			else
				return group.get(groupPosition);
		}
		//获取与给定的元素在给定的组中相关联的数据
		@Override
		public User getChild(int groupPosition, int childPosition) {
			if(child == null)
				return null;
			else
				return child.get(groupPosition).get(childPosition);
		}
		//获取组在给定的位置ID
		@Override
		public long getGroupId(int groupPosition) {
			return groupPosition;
		}
		//获取元素在给定的组中的ID
		@Override
		public long getChildId(int groupPosition, int childPosition) {
			return childPosition;
		}

		//指元素ID和组ID在操作底层的数据改变时是否改变的
		@Override
		public boolean hasStableIds() {
			return false;
		}
		//当这个组展开时调用这个函数
		@Override
		public void onGroupExpanded(int groupPosition) {
			// TODO Auto-generated method stub
			super.onGroupExpanded(groupPosition);
			listView.setSelectedGroup(groupPosition);
		}
		//得到组的那个选项视图
		@Override
		public View getGroupView(int groupPosition, boolean isExpanded,
				View convertView, ViewGroup parent) {
			if(group.size()==0)
				return null;
			if (group!=null && groupPosition >= group.size()) {
				return null;
			}
			if (convertView == null) {
				convertView = mLayoutInflater.inflate(R.layout.list_group_view, null, false);
				groupHolder = new GroupViewHolder();
				groupHolder.icon = (ImageView) convertView.findViewById(R.id.list_group_view_header_icon);
				groupHolder.name = (TextView) convertView.findViewById(R.id.list_group_view_group_name);
				convertView.setTag(groupHolder);
			} else {
				groupHolder = (GroupViewHolder) convertView.getTag();
			}	
			
			String string = group.get(groupPosition);
//			String GroupName = string.substring(0, string.indexOf("[")).trim();
//			String onlineNum = string.substring(string.indexOf("[")).trim();
			SpannableStringBuilder spannable=new SpannableStringBuilder(string);//用于可变字符串  
	        ForegroundColorSpan span=new ForegroundColorSpan(getResources().getColor(R.color.color_white)); 
	        TextAppearanceSpan css = new TextAppearanceSpan(ScreenFriendList.this, android.R.style.TextAppearance_Small_Inverse, getResources().getColor(R.color.color_gray)); 
	        spannable.setSpan(css, string.indexOf("["), string.length(), Spannable.SPAN_INCLUSIVE_INCLUSIVE);
			if(isExpanded)
				groupHolder.icon.setImageResource(R.drawable.list_open);
			else
				groupHolder.icon.setImageResource(R.drawable.list_close);
			groupHolder.name.setTextColor(ScreenFriendList.this.getResources().getColor(R.color.color_white));
			groupHolder.name.setText(spannable);
            return convertView;
		}
		
		//View stub to create Group/Children 's View   
        private TextView getGenericView(String s) {   
            // Layout parameters for the ExpandableListView   
            AbsListView.LayoutParams lp = new AbsListView.LayoutParams(   
                    ViewGroup.LayoutParams.FILL_PARENT, 64);   
  
            TextView text = new TextView(activity);   
            text.setLayoutParams(lp);   
            // Center the text vertically   
            text.setGravity(Gravity.CENTER_VERTICAL | Gravity.LEFT);   
            // Set the text starting position   
            text.setPadding(60, 0, 0, 0);
               
            text.setText(s);
            text.setTextColor(Color.BLACK);
            return text;   
        } 

      //得到组中显示元素的视图
		@Override
		public View getChildView(int groupPosition, int childPosition,
				boolean isLastChild, View convertView, ViewGroup parent) {
			if(child == null || child.size()==0)
				return null;
			if (groupPosition >= child.size() || childPosition >= child.get(groupPosition).size()) {
				return null;
			}
			if (convertView == null) {
				convertView = mLayoutInflater.inflate(R.layout.screen_friend_list_item, null, false);
				holder = new ViewHolder();
				holder.icon = (ImageView) convertView.findViewById(R.id.user_icon);
				holder.name = (TextView) convertView.findViewById(R.id.user_nickName);
				holder.id = (TextView) convertView.findViewById(R.id.user_id);
			    holder.ivLook = (ImageButton) convertView.findViewById(R.id.user_look);
			    holder.ivSay = (ImageButton) convertView.findViewById(R.id.user_say);
			    holder.ivMsg = (ImageButton) convertView.findViewById(R.id.user_message);
				convertView.setTag(holder);
			} else {
				holder = (ViewHolder) convertView.getTag();
			}			
			
			User user = child.get(groupPosition).get(childPosition);			

			int iconRES;
			int onlineRES;
			iconRES = R.drawable.friend_dot;
			if(user.getOnlineStatus() == Type.available) {
				ColorMatrix colorMatrix = new ColorMatrix();
				colorMatrix.setSaturation(1);
				ColorMatrixColorFilter colorMatrixFilter = new ColorMatrixColorFilter(
				colorMatrix);
				holder.icon.setColorFilter(colorMatrixFilter);
				holder.name.setTextColor(ScreenFriendList.this.getResources().getColor(R.color.color_black));
			} else {
				ColorMatrix colorMatrix = new ColorMatrix();
				colorMatrix.setSaturation(0);
				ColorMatrixColorFilter colorMatrixFilter = new ColorMatrixColorFilter(
				colorMatrix);
				holder.icon.setColorFilter(colorMatrixFilter);
				holder.name.setTextColor(ScreenFriendList.this.getResources().getColor(R.color.color_gray));
			}
			holder.icon.setBackgroundResource(R.drawable.avatar_bg);
			holder.icon.setImageResource(iconRES);
			holder.icon.setScaleType(ScaleType.FIT_CENTER);
			holder.icon.setImageResource(iconRES);
			holder.name.setText(user.getDisplayName());
			holder.id.setText(user.getOnlineStatus()+"");
			final Intent i=new Intent(ScreenFriendList.this, showFriendInfoPage.class);
			i.putExtra("nickname",user.getNickName());
			i.putExtra("id",user.getJID());
			i.putExtra("sex",user.getSex());
			i.putExtra("address",user.getAddress());
			i.putExtra("age",user.getAge());
			i.putExtra("notename",user.getNoteName());
			holder.ivLook.setOnClickListener(new OnClickListener() {
				
				@Override
				public void onClick(View v) {
					startActivity(i);
				}
			});
			holder.ivSay.setOnClickListener(new OnClickListener() {
				
				@Override
				public void onClick(View v) {
					startActivity(i);
				}
			});
			holder.ivMsg.setOnClickListener(new OnClickListener() {
				
				@Override
				public void onClick(View v) {
					startActivity(i);
				}
			});
//			holder.tip.setOnClickListener(new ButtonClickListener(groupPosition, childPosition));
			return convertView;
		}
		//元素在指定位置是否是可选择的
		@Override
		public boolean isChildSelectable(int groupPosition, int childPosition) {
			return true;
		}
	}	
	
	/**
	 * 监听文件传输
	 */
	public void setFileListener(final XMPPConnection conn) {
		Thread thread = new Thread() {
			public void run() {
				//Discovery：发现
				ServiceDiscoveryManager sdm = ServiceDiscoveryManager
						.getInstanceFor(conn);//拿到关于这个连接的管理发现服务
				if (sdm == null)
					sdm = new ServiceDiscoveryManager(conn);
				sdm.addFeature("http://jabber.org/protocol/disco#info");//Feature：特征
				sdm.addFeature("jabber:iq:privacy");
				/*
				 * Create the file transfer manager（创建这文件传输的管理）
				 * Transfer:转让；转移；传递
				 * 拿到关于这个连接的文件传递管理
				 */
				final FileTransferManager managerListner = new FileTransferManager(
						conn);
				 //Enabled:激活的；可行的,Negotiator:谈判者,交涉者
				                         //这个元素既没有附加的原始资料也没有说明因此是否创建说明
				FileTransferNegotiator.setServiceEnabled(conn, true);
				Log.i("File transfere manager", "created");
				// Create the listener
				managerListner
						.addFileTransferListener(new FileTransferListener() {//Listener:监听器
							@Override
							public void fileTransferRequest(
									FileTransferRequest request) {
								String JID = request.getRequestor();
								String from = JID.substring(0, JID.indexOf("@"));
								sTip = "是否接收来自XXX的文件FFF".replace("XXX",	from);
								sTip = sTip.replace("FFF", request.getFileName());				
								sRequest = request;
								ListHander.sendEmptyMessage(SCREEN_HOME_HANDLE_FILE_TRANSFER);
								setReceiveFileFrom(JID.substring(0, JID.indexOf("/")));								
							}
						});
			}
		};
		thread.start();
	} 
	
	private String mFileFrom;
	private void setReceiveFileFrom(String from) {
		mFileFrom = from;
	}
	
	private void receiveFileHistory(String content) {
		// 收消息
		NgnHistorySMSEvent event = new NgnHistorySMSEvent(mFileFrom, StatusType.Incoming);
		event.setContent(content);
		getEngine().getHistoryService().addEvent(event);
		ScreenChat.currentChatList.add(event);
		if(ScreenChat.instance!=null)
			ScreenChat.instance.refreshFromServer();
	}
}
